package com.five.core.handler;

import com.five.core.exception.CustomerException;
import com.five.core.result.Result;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 全局异常处理
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 参数校验异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result handleValidationException(MethodArgumentNotValidException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        StringBuilder msg = new StringBuilder();
        for (FieldError fieldError : fieldErrors) {
            msg.append(fieldError.getDefaultMessage()).append(";");
        }
        return Result.buildFail(msg.toString());
    }

    @ExceptionHandler(CustomerException.class)
    public Result handleCustomerException(CustomerException e) {
        return Result.buildFail(e.getResultEnum());
    }
}
